package com.xincheng.shuimalong.activity.recept;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.IdRes;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.xincheng.library.util.ClipBoardUtil;
import com.xincheng.library.util.CommonUtil;
import com.xincheng.library.util.PrefUtil;
import com.xincheng.library.util.UIUtil;
import com.xincheng.library.widget.StateButton;
import com.xincheng.library.widget.alertview.AlertView;
import com.xincheng.library.widget.alertview.OnAlertItemClickListener;
import com.xincheng.library.widget.pickerview.OptionsPickerView;
import com.xincheng.library.xlog.XLog;
import com.xincheng.shuimalong.R;
import com.xincheng.shuimalong.activity.BaseActivity;
import com.xincheng.shuimalong.activity.OrderDetailActivity;
import com.xincheng.shuimalong.activity.UploadImageActivity;
import com.xincheng.shuimalong.api.AppUrl;
import com.xincheng.shuimalong.api.BaseObserver;
import com.xincheng.shuimalong.api.GetParam;
import com.xincheng.shuimalong.api.PostParam;
import com.xincheng.shuimalong.api.RetroSubscrube;
import com.xincheng.shuimalong.common.Constant;
import com.xincheng.shuimalong.common.IntentKey;
import com.xincheng.shuimalong.common.PrefKey;
import com.xincheng.shuimalong.common.RequestCodeKey;
import com.xincheng.shuimalong.entity.OrderDetail;
import com.xincheng.shuimalong.entity.config.CommonConfig;
import com.xincheng.shuimalong.entity.config.CompanyLogo;
import com.xincheng.shuimalong.manager.GlideOptionsManager;
import com.xincheng.shuimalong.util.BitmapUtil;
import com.xincheng.shuimalong.util.ConfigUtil;
import com.xincheng.shuimalong.util.GsonUtil;
import com.xincheng.shuimalong.util.MyUtil;
import com.xincheng.shuimalong.util.ShowActivity;

import java.io.File;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.annotations.NonNull;

/**
 * Created by xiaote on 2017/7/4.
 * 待出单详情
 */

public class ReceiptIssueActivity extends BaseActivity {
    @BindView(R.id.order_detail_status_tv)
    TextView mStatusTv;
    @BindView(R.id.order_detail_orderno_tv)
    TextView mOrderNoTv;
    @BindView(R.id.order_detail_updatetime_tv)
    TextView mUpdateTimeTv;
    @BindView(R.id.receipt_issue_pay_money_tv)
    TextView mPayMoneyTv;
    @BindView(R.id.receipt_issue_pay_date_tv)
    TextView mPayDateTv;
    @BindView(R.id.receipt_issue_vci_guarantee_et)
    EditText mVciGuaranteeEt;
    @BindView(R.id.receipt_issue_tci_guarantee_et)
    EditText mTciGuranteeEt;
    @BindView(R.id.receipt_issue_express_rg)
    RadioGroup mExpressRg;
    @BindView(R.id.receipt_issue_express_layout)
    LinearLayout mExpressLayout;
    @BindView(R.id.express_choose_tv)
    TextView mExpressChooseTv;
    @BindView(R.id.express_no_et)
    TextView mExpressNoEt;
    //名称 头像 手机号码 保险logo
    @BindView(R.id.iv_avatar)
    ImageView ivAvatar;
    @BindView(R.id.tv_order_name)
    TextView tvOrderName;
    @BindView(R.id.tv_order_phone)
    TextView tvOrderPhone;
    @BindView(R.id.iv_insurance_img)
    ImageView ivInsuranceImg;
    @BindView(R.id.receipt_issue_accept_btn)
    StateButton mAcceptBtn;
    @BindView(R.id.receipt_issue_submit_btn)
    StateButton mIssueBtn;


    private String mToken;
    private int mBidId;
    private OrderDetail mOrderDetail;
    private long mCreateTime;

    private List<CommonConfig> mExpressTypes;
    private List<CommonConfig> mExpressCompanys;
    private OptionsPickerView<CommonConfig> mExpressCompanyPicker;
    private String mVciGuaranteeImgPath = "";
    private String mTciGuaranteeImgPath = "";
    private int mExpressTypeId;
    private String mVciNo = "", mTciNo = "";
    private String mVciCt = "", mTciCt = "";
    private int mExpressCompanyId = 0;
    private String mExpressNo = "";

    @Override
    public int getLayoutResId() {
        return R.layout.activity_receipt_issue;
    }

    @Override
    public void initData() {
        initTitleBar(getString(R.string.order_detail1));
        mToken = PrefUtil.getString(this, PrefKey.TOKEN, "");
        Bundle extras = getIntent().getExtras();
        mBidId = extras.getInt(IntentKey.BID_ID, 0);
        mCreateTime = extras.getLong(IntentKey.CREATE_TIME);
        mOrderNoTv.setText(getString(R.string.order_no, ""));
        mExpressTypes = ConfigUtil.getCommonConfigList(this, PrefKey.EXPRESS_TYPE);
        mExpressCompanys = ConfigUtil.getCommonConfigList(this, PrefKey.EXPRESS_COMPANYS);
        mExpressTypeId = mExpressTypes.get(1).getId();
        tvOrderName.setText(extras.getString(IntentKey.NICK_NAME));
        tvOrderPhone.setText(extras.getString(IntentKey.MOBILE));
        Glide.with(getContext()).load(extras.getString(IntentKey.AVATAR)).apply(GlideOptionsManager.getInstance()
                .getRequestOptions()).into(ivAvatar);
        initPicker();
        getOrderDetail();
    }

    private void initPicker() {
        mExpressCompanyPicker = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                CommonConfig expressCompany = mExpressCompanys.get(options1);
                mExpressCompanyId = expressCompany.getId();
                mExpressChooseTv.setText(expressCompany.getPickerViewText());
            }
        }).setTitleText(getString(R.string.express_choose)).build();
        mExpressCompanyPicker.setPicker(mExpressCompanys);
    }

    @OnClick({R.id.receipt_issue_orderdetail_tv, R.id.receipt_issue_upload_guarantee_iv,
            R.id.express_choose_tv, R.id.receipt_issue_accept_btn, R.id.receipt_issue_submit_btn,
            R.id.tv_order_phone})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.receipt_issue_orderdetail_tv://查看订单详情
                if (mOrderDetail != null) {
                    Bundle extras = new Bundle();
                    extras.putInt(IntentKey.FROM, 1);
                    extras.putLong(IntentKey.CREATE_TIME, mCreateTime);
                    extras.putParcelable(IntentKey.ORDER_DETAIL, mOrderDetail);
                    ShowActivity.showActivity(this, OrderDetailActivity.class, extras);
                }
                break;
            case R.id.receipt_issue_upload_guarantee_iv://上传保单图片
                Bundle extras = new Bundle();
                extras.putInt(IntentKey.FROM, 3);
                extras.putString(IntentKey.UPLOAD_IMG_PATH1, mVciGuaranteeImgPath);
                extras.putString(IntentKey.UPLOAD_IMG_PATH2, mTciGuaranteeImgPath);
                ShowActivity.showActivityForResult(this, UploadImageActivity.class, extras,
                        RequestCodeKey.GO_UPLOAD_IMG);
                break;
            case R.id.express_choose_tv://选择快递公司
                if (mExpressCompanyPicker != null) {
                    mExpressCompanyPicker.show();
                }
                break;
            case R.id.tv_order_phone:
                if (CommonUtil.isEmpty(tvOrderPhone)) {
                    showToast("抱歉，没有联系方式");
                    return;
                }
                String mobile_phone = tvOrderPhone.getText().toString().trim();
                showCallAlert(mobile_phone);
                break;
            case R.id.receipt_issue_accept_btn://接受出单
                confirmAccept();
                break;
            case R.id.receipt_issue_submit_btn://确认出单
                if (checkData()) {
                    mTciNo = mTciGuranteeEt.getText().toString().trim();
                    mVciNo = mVciGuaranteeEt.getText().toString().trim();
                    if (mTciNo.equals(mVciNo)) {
                        showToast("保单号不能相同");
                        return;
                    }
                    mExpressNo = mExpressNoEt.getText().toString().trim();
                    issue();
                }
                break;
        }
    }

    private void confirmAccept() {
        RetroSubscrube.getInstance().postSubscrube(AppUrl.CONFIRM_ACCEPT, PostParam.confirmAccept(mToken, mBidId),
                new BaseObserver(this, getString(R.string.loading_submit)) {
                    @Override
                    protected void onHandleSuccess(Object data, String msg) {
                        showToast(msg);
                        Intent intent = new Intent();
                        intent.putExtra(IntentKey.ISSUE_SUCCESS, true);
                        setResult(RESULT_OK, intent);
                        finish();
                    }
                });
    }

    private void issue() {
        RetroSubscrube.getInstance().postSubscrube(AppUrl.GIVE_ISSUE,
                PostParam.giveIssue(mToken, mBidId, mTciCt, mVciCt, mTciNo, mVciNo, mExpressTypeId,
                        mExpressCompanyId, mExpressNo),
                new BaseObserver(this, getString(R.string.loading_submit)) {
                    @Override
                    protected void onHandleSuccess(Object data, String msg) {
                        showToast(msg);
                        Intent intent = new Intent();
                        intent.putExtra(IntentKey.ISSUE_SUCCESS, true);
                        setResult(RESULT_OK, intent);
                        finish();
                    }

                    @Override
                    protected void onHandleError(String msg) {
                        showErrorMsg(msg);
                    }
                });
    }

    private void showCallAlert(final String mobile) {
        new AlertView(this, null, null, getString(R.string.cancel), null, Constant.CALL_WAY,
                AlertView.Style.ActionSheet, new OnAlertItemClickListener() {
            @Override
            public void onItemClick(AlertView alertView, int position) {
                switch (position) {
                    case 0: //呼叫
                        ShowActivity.callPhone(getContext(), mobile);
                        break;
                    case 1: //复制号码
                        ClipBoardUtil.copyText(getContext(), mobile);
                        break;
                    case 2: //添加到通讯录
                        ShowActivity.addContact(getContext(), mobile);
                        break;
                }
            }
        }).show();
    }

    private void showErrorMsg(String msg) {
        AlertView alertView = new AlertView(this, null, msg, getString(R.string.cancel),
                new String[]{getString(R.string.confirm)}, null, AlertView.Style.Alert, null);
        alertView.show();
    }

    private boolean checkData() {
        if (CommonUtil.isEmpty(mVciCt)) {
            showToast("请上传商业险保单图片");
            return false;
        }
        if (CommonUtil.isEmpty(mTciCt)) {
            showToast("请上传较交强险保单图片");
            return false;
        }
        if (CommonUtil.isEmpty(mVciGuaranteeEt)) {
            showToast("商业险保单号不能为空");
            return false;
        }
        if (CommonUtil.isEmpty(mTciGuranteeEt)) {
            showToast("交强险保单号不能为空");
            return false;
        }
        if (mExpressTypeId == mExpressTypes.get(1).getId()) {
            if (CommonUtil.isEmpty(mExpressChooseTv)) {
                showToast("快递公司不能为空");
                return false;
            }
            if (CommonUtil.isEmpty(mExpressNoEt)) {
                showToast("快递单号不能为空");
                return false;
            }
            if (mExpressNoEt.length() > 20) {
                showToast("快递单号最长20位");
                return false;
            }
        }
        return true;
    }

    private void getBase64Data() {
        if (!CommonUtil.isEmpty(mVciGuaranteeImgPath)) {
            Glide.with(this).asBitmap().load(mVciGuaranteeImgPath).into(new SimpleTarget<Bitmap>() {
                @Override
                public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
                    Bitmap bitmap = resource;
                    if (resource != null && resource.getWidth() > Constant.UPLOAD_IMAGE_SIZE_DEFAULT) {
                        bitmap = BitmapUtil.zoomImg(resource, Constant.UPLOAD_IMAGE_SIZE_DEFAULT);
                    }
                    mVciCt = BitmapUtil.bitmapToBase64(bitmap);
                }
            });
        }
        if (!CommonUtil.isEmpty(mTciGuaranteeImgPath)) {
            Glide.with(this).asBitmap().load(mTciGuaranteeImgPath).into(new SimpleTarget<Bitmap>() {
                @Override
                public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
                    Bitmap bitmap = resource;
                    if (resource != null && resource.getWidth() > Constant.UPLOAD_IMAGE_SIZE_DEFAULT) {
                        bitmap = BitmapUtil.zoomImg(resource, Constant.UPLOAD_IMAGE_SIZE_DEFAULT);
                    }
                    mTciCt = BitmapUtil.bitmapToBase64(bitmap);
                }
            });
        }
    }

    private void getOrderDetail() {
        RetroSubscrube.getInstance().getSubscrube(GetParam.viewAcOrder(mToken, mBidId),
                new BaseObserver(this, getString(R.string.loading_data)) {
                    @Override
                    protected void onHandleSuccess(Object data, String msg) {
                        if (data != null) {
                            mOrderDetail = GsonUtil.parseData(data, OrderDetail.class);
                            parseOrderDetail();
                        }
                    }
                });
    }

    private void parseOrderDetail() {
        mStatusTv.setText("待出单");
        mOrderNoTv.setText(getString(R.string.order_no, mOrderDetail.getOrderNo()));
        mUpdateTimeTv.setText(mOrderDetail.getUpdateTime());
        mPayMoneyTv.setText(getString(R.string.money_value, mOrderDetail.getTotalMoney()));
        mPayDateTv.setText(mOrderDetail.getPayTime());
        CompanyLogo companyLogo = ConfigUtil.getCompanyLogoById(this, mOrderDetail.getCompanyId());
        final int screenWith = UIUtil.getDisplaySize(this)[0];
        if (companyLogo != null) {
            Glide.with(this).asBitmap().load(companyLogo.getLogo()).into(new SimpleTarget<Bitmap>() {
                @Override
                public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
                    Bitmap bitmap = BitmapUtil.zoomImg(resource, screenWith / 3);
                    ivInsuranceImg.setImageBitmap(bitmap);
                }
            });
        }
        if(mOrderDetail.getConfirmAccept() == 1) {
            mAcceptBtn.setVisibility(View.GONE);
            mIssueBtn.setText(getString(R.string.issue_confirm));
        } else {
            mAcceptBtn.setVisibility(View.VISIBLE);
            mIssueBtn.setText(getString(R.string.issue_directly));
        }
    }

    @Override
    public void addListener() {
        mExpressRg.setOnCheckedChangeListener(new MyOnCheckedChangedListener());
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case RequestCodeKey.GO_UPLOAD_IMG:
                    mVciGuaranteeImgPath = data.getStringExtra(IntentKey.UPLOAD_IMG_PATH1);
                    mTciGuaranteeImgPath = data.getStringExtra(IntentKey.UPLOAD_IMG_PATH2);
                    getBase64Data();
                    break;
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private class MyOnCheckedChangedListener implements RadioGroup.OnCheckedChangeListener {

        @Override
        public void onCheckedChanged(RadioGroup radioGroup, @IdRes int checkId) {
            switch (checkId) {
                case R.id.receipt_issue_express_toface_rb:
                    mExpressTypeId = mExpressTypes.get(0).getId();
                    mExpressLayout.setVisibility(View.GONE);
                    break;
                case R.id.receipt_issue_express_mail_rb:
                    mExpressTypeId = mExpressTypes.get(1).getId();
                    mExpressLayout.setVisibility(View.VISIBLE);
                    break;
            }
        }
    }
}
